package com.ssm.sport.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ssm.sport.service.UserService;
import com.ssm.sport.entity.User;

/**
 * 用户认证拦截器
 * 通过请求参数或请求头传入用户ID进行认证
 */
public class UserAuthInterceptor implements HandlerInterceptor {
    
    private static final Logger logger = LoggerFactory.getLogger(UserAuthInterceptor.class);
    
    @Autowired
    private UserService userService;
    
    // 用户ID的参数名
    private static final String USER_ID_PARAM = "userId";
    
    // 用户ID的请求头名
    private static final String USER_ID_HEADER = "X-User-Id";
    
    // 用户对象存储在请求属性中的名称
    private static final String USER_ATTRIBUTE = "currentUser";
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求参数获取用户ID
        String userId = request.getParameter(USER_ID_PARAM);
        
        // 如果请求参数中没有，则从请求头获取
        if (StringUtils.isEmpty(userId)) {
            userId = request.getHeader(USER_ID_HEADER);
        }
        
        // 如果没有传入用户ID，则允许请求继续（可能是公开接口）
        if (StringUtils.isEmpty(userId)) {
            logger.debug("No user ID provided, continuing as anonymous user");
            return true;
        }
        
        try {
            // 通过用户ID查询用户信息
            User user = userService.getById(Integer.parseInt(userId));
            
            if (user != null) {
                // 将用户信息存储在请求属性中，便于后续使用
                request.setAttribute(USER_ATTRIBUTE, user);
                logger.debug("User authenticated: {}", user.getUsername());
                return true;
            } else {
                logger.warn("Invalid user ID provided: {}", userId);
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid user ID");
                return false;
            }
        } catch (NumberFormatException e) {
            logger.warn("Invalid user ID format: {}", userId);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid user ID format");
            return false;
        } catch (Exception e) {
            logger.error("Error authenticating user: {}", userId, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Authentication error");
            return false;
        }
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 不需要特殊处理
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理资源
    }
    
    /**
     * 从请求中获取当前用户
     * @param request HTTP请求
     * @return 当前用户对象，如果未认证则返回null
     */
    public static User getCurrentUser(HttpServletRequest request) {
        return (User) request.getAttribute(USER_ATTRIBUTE);
    }
} 